
import {
	HTTP_REQUEST_URL,
	HEADER,
	TOKENNAME
} from '@/config/app';
import {
	toLogin,
	checkLogin
} from '../libs/login';
import store from '@/store';


function baseRequest(srv, url, method, data, {
	noAuth = false,
	noVerify = false
}) {
	let Url = srv,
		header = HEADER;

	if (!noAuth) {
		if (!store.state.app.token && !checkLogin()) {
			toLogin();
			return Promise.reject({
				msg: '未登录'
			});
		}
	}

	if (store.state.app.token) header[TOKENNAME] = 'Bearer ' + store.state.app.token;

	return new Promise((reslove, reject) => {
		uni.request({
			url: Url + '/api/' + url,
			method: method || 'GET',
			header: header,
			data: data || {},
			success: (res) => {
				// #ifdef APP-PLUS
				console.log('app', Url + '/api/' + url, res.data);
				// #endif
				if (noVerify)
					reslove(res.data, res);
				else if (res.data.errcode == 0)
					reslove(res.data, res);
				else if (res.data.errcode == 410000) {
					toLogin();
					reject(res.data);
				} else
					reject(res.data);
			},
			fail: (message) => {
				reject({msg: '请求失败：' + message});
			}
		})
	});
}


const request = {};

['options', 'get', 'post', 'put', 'head', 'delete', 'trace', 'connect'].forEach((method) => {
	request[method] = (srv, api, data, opt) => baseRequest(srv, api, method, data, opt || {})
});

const fshsrv = "https://crmeb-test.mer.chuidiaotop.com"; //切换环境
// const fshsrv = "https://mer.chuidiaotop.com";

export function loadIndexPageData() {
  return request.get(fshsrv, "fshsrv/mp/loadIndexPageData", {}, {noAuth:true});
}

export function loadIndexFshData(lastRetFshLogIds) {
  return request.get(fshsrv, "fshsrv/mp/loadIndexFshData", {lastRetFshLogIds}, {noAuth:true});
}

export function queryLotteryRules(productId) {
	return request.get(fshsrv, "fshsrv/manage/queryLotteryRules", {productId});
}

export function addLotteryRule(pondId, partitionId, seatMode, seatRangeType, lotteryNumber, applyToDaysOfWeek) {
	return request.get(fshsrv, "fshsrv/manage/addLotteryRule", {pondId, partitionId, seatMode, seatRangeType, lotteryNumber, applyToDaysOfWeek});
}

export function softDeleteLotteryRule(pondId, id, delFlag) {
	return request.get(fshsrv, "fshsrv/manage/softDeleteLotteryRule", {pondId, id, delFlag});
}

export function getSeatsForLottery(odId) {
	return request.get(fshsrv, "fshsrv/mp/getSeatsForLottery", {odId});
}

export function doLottery(odId,isChangeSeat) {
	return request.get(fshsrv, "fshsrv/mp/doLottery", {odId, isChangeSeat});
}

export function querySeatsForSelect(ypOdId) {
  return request.get(fshsrv, "fshsrv/mp/querySeatsForSelect?odId="+ypOdId);
}

export function bindSeatToOrder(ypOdId, seatId) {
  return request.get(fshsrv, "gzyxsrv/mp/bindSeatToOrder?odId="+ypOdId+"&seatId="+seatId);
}

export function bindSeatToOrderV2(ypOdId, seatId, cmhDebugUserId) {
  return request.get(fshsrv, "gzyxsrv/mp/bindSeatToOrderV2?odId="+ypOdId+"&seatId="+seatId, {cmhDebugUserId});
}

export function openFshPage(specOdId) {
  return request.get(fshsrv, "fshsrv/mp/openFshPage"+(specOdId?("?specOdId="+specOdId):""));
}

export function queryMyOrders(filterType, pageNum, seatId) {
	let param = {filterType, pageNum};
	if(seatId)
		param.seatId = seatId;
  return request.get(fshsrv, "fshsrv/mp/queryMyOrders", param);
}

export function queryRetLogs(ypOdId, deviceSn) {
	if(ypOdId)
		return request.get(fshsrv, "fshsrv/mp/queryRetLogs?odId="+ypOdId);
	else 
		return request.get(fshsrv, "fshsrv/mp/queryRetLogs?deviceSn="+deviceSn);
}

export function doFshAction(specOdId, action) {
  return request.get(fshsrv, "gzyxsrv/device/doFshAction?specOdId="+specOdId+"&action="+action);
}

export function queryForRetFsh(merId) {
  return request.get(fshsrv, "fshsrv/mp/queryForRetFsh", {merId});
}

export function retFsh(odId, number, weight, takeawayWeight, remarks, onlyRetFsh=false) {
  return request.get(fshsrv, "fshsrv/mp/retFsh", {odId, number, weight, takeawayWeight, remarks, onlyRetFsh});
}

export function queryFshBills(type, pageNum, pageSize) {
  return request.get(fshsrv, "fshsrv/mp/queryFshBills", {type, pageNum, pageSize});
}

export function queryFshGrounds(sortType, pageNum, latitude, longitude) {
	let queryDto = {
	  sortType,
	  pageNum,
	  latitude,
	  longitude
	}
  return request.get(fshsrv, "fshsrv/mp/queryFshGrounds", {jsonParam:JSON.stringify(queryDto)}, {noAuth:true});
}

export function loadFshGroundHomePage(merId) {
  return request.get(fshsrv, "fshsrv/mp/loadFshGroundHomePage", {merId});
}

export function queryGoodsByFshGround(merId, pageNum) {
  let queryDto = {
	  criteriaDto: {
		  merId
	  },
    pageNum,
  }
  return request.get(fshsrv, "fshsrv/mp/queryGoodsByFshGround", {jsonParam:JSON.stringify(queryDto)});
}

export function queryFshRanks(type, merId, productId) {
	return request.get(fshsrv, "fshsrv/mp/queryFshRanks", {type, merId, productId});
}

export function queryFshRanks2(merId, pondId, partitionId, sku) {
	return request.get(fshsrv, "fshsrv/mp/queryFshRanks2", {merId, pondId, partitionId, sku});
}

export function queryFshRanksByProd(merId, prodId) {
	return request.get(fshsrv, "fshsrv/mp/queryFshRanksByProd", {merId, prodId});
}

export function changeSeat_isPaid(odId) {
  return request.get(fshsrv, "gzyxsrv/mp/changeSeat/isPaid?odId="+odId);
}

export function changeSeat_prepairPay(odId) {
  return request.get(fshsrv, "gzyxsrv/mp/changeSeat/prepairPay?odId="+odId);
}

export function changeSeat_bind(odId, seatId) {
  return request.get(fshsrv, "gzyxsrv/mp/changeSeat/bind?odId="+odId+"&seatId="+seatId);
}

/* 
export function queryRaces(sortType, pageNum) {  // 对应后端FshCustomServiceImpl::queryRaces
	let queryDto = {
	  sortType,
	  pageNum
	}
  return request.get(fshsrv, "fshsrv/mp/queryRaces", {jsonParam:JSON.stringify(queryDto)}, {noAuth:true});
}
*/
export function queryRaces(queryType, sortType, pageNum, raceId) {
	let queryDto = {
	  queryType, // 1-赛事首页查询，2-查询我的比赛，3-查询我的发布
	  sortType, // 当queryType=1时: 1-查询附近比赛，2-查询关注比赛
	  pageNum, // 分页编号，以1为基
	  raceId, // race_manage_edit_info发布比赛后查询时会指定raceId
	}
  return request.get(fshsrv, "fshsrv/mp/race/queryRaces", queryDto, {noAuth:queryType==1});
}

export function getRaceById(raceId) {
	// pub_getRaceDetail
  return request.get(fshsrv, "fshsrv/mp/race/getRaceById", {raceId}, {noAuth:true});
}

export function raceDeductPoints(raceId, round, partition, userId, points) {
  return request.get(fshsrv, "fshsrv/mp/race/raceDeductPoints", {raceId, round, partition, userId, points});
}

export function raceModifyRace(raceId, round, partition, userId, modifyWeight, modifyNumber) {
  return request.get(fshsrv, "fshsrv/mp/race/raceModifyRace", {raceId, round, partition, userId, modifyWeight, modifyNumber});
}

export function getMyServiceMerchants() {
  return request.get(fshsrv, "fshsrv/mp/getMyServiceMerchants");
}

export function getRaceCateId() {
  return request.get(fshsrv, "fshsrv/mp/race/getRaceCateId");
}

// type: 0-报名, 1-签到
export function changeRaceSignStatus(raceId, type, currStatus, newStatus) {
  return request.get(fshsrv, "fshsrv/mp/race/changeRaceSignStatus", {raceId, type, currStatus, newStatus});
}

// type: 0-报名, 1-签到
export function getSignPlayers(raceId, type) {
  return request.get(fshsrv, "fshsrv/mp/race/getSignPlayers", {raceId, type});
}

export function auditRacePlayers(raceId, ids, auditState) {
  return request.get(fshsrv, "fshsrv/mp/race/auditRacePlayers", {raceId, ids, auditState});
}

export function queryForEditRound(merId, raceId) {
  return request.get(fshsrv, "fshsrv/mp/race/queryForEditRound", {merId, raceId});
}

export function saveForEditRound(raceId, data) {
  return request.get(fshsrv, "fshsrv/mp/race/saveForEditRound", {raceId, ...data});
}

export function softDeleteRace(raceId, prodId) {
  return request.get(fshsrv, "fshsrv/mp/race/softDeleteRace", {raceId, prodId});
}

export function resetRace(raceId, prodId) {
  return request.get(fshsrv, "gzyxsrv/mp/race/resetRace", {raceId, prodId});
}

export function openLottery(raceId, type) {
  return request.get(fshsrv, "gzyxsrv/mp/race/changeStatue", {raceId, type});
}

export function getRaceForDrawLots(raceId) {
  return request.get(fshsrv, "fshsrv/mp/race/getRaceForDrawLots", {raceId});
}

export function signIn(raceId) {
	return request.get(fshsrv, "fshsrv/mp/race/signIn", {raceId});
}

export function prepairDrawLottery(raceId, round) {
	return request.get(fshsrv, "fshsrv/mp/race/prepairDrawLottery", {raceId, round});
}

export function submitDrawLottery(raceId, round) {
	return request.get(fshsrv, "fshsrv/mp/race/submitDrawLottery", {raceId, round});
}

export function openRoundLottery(raceId, round, onOff) {
	return request.get(fshsrv, "fshsrv/mp/race/openRoundLottery", {raceId, round, onOff});
}

export function showDrawLottery(raceId) {
	return request.get(fshsrv, "fshsrv/mp/race/showDrawLottery", {raceId});
}

export function resetRoundLottery(raceId, round) {
	return request.get(fshsrv, "fshsrv/mp/race/resetRoundLottery", {raceId, round});
}

export function queryDevices(searchKeyword, deviceUsingState, deviceOnlineState, deviceBindState, pageNum, orderByDeviceSn, orderByOnlineTime, orderByOfflineTime) {
  let queryDto = {
	  searchKeyword,
	  deviceUsingState, deviceOnlineState, deviceBindState, 
	  pageNum,
	  orderByDeviceSn, orderByOnlineTime, orderByOfflineTime
  }
  return request.get(fshsrv, "gzyxsrv/mp/queryDevices", {jsonParam:JSON.stringify(queryDto)});
}

export function queryMerSeatsForBind(pageNum) {
  let queryDto = {
	  criteriaDto: {
	  },
	pageNum,
  }
  return request.get(fshsrv, "fshsrv/mp/queryMerSeatsForBind", {jsonParam:JSON.stringify(queryDto)});
}

export function querySlideImgs(type) {
  return request.get(fshsrv, "fshsrv/mp/querySlideImgs", {type}, {noAuth:true});
}

export function getDeviceInfo(device) {
	return request.get(fshsrv, "fshsrv/mp/getDeviceInfo", {device});
}

export function setupDevice(action, devices, binds) {
	let param = {action, devices, binds};
  return request.get(fshsrv, "gzyxsrv/mp/setupDevice", { josnParam:JSON.stringify(param)});
}

export function bindDeviceSeat(deviceSn, seatId, seatNo) {
	let binds = [{
		deviceSn: deviceSn,
		seatId: seatId, 
		seatNo: seatNo
	}] 
  return setupDevice('bindDeviceSeat', null, binds);
}

export function unbindDeviceSeat(deviceSn, seatId, seatNo) {
  return setupDevice('unbindDeviceSeat', [{deviceSn}], null);
}

export function disableSeats(pondId, partitionId, fromSeatNo, toSeatNo, disable) {
	disable = disable?1:0;
  return request.get(fshsrv, "fshsrv/mp/disableSeats", {pondId, partitionId, fromSeatNo, toSeatNo, disable});
}

export function getMyMerchants() {
  return request.get(fshsrv, "fshsrv/mp/getMyMerchants", {});
}

export function updateMerchant(data) {
  return request.post(fshsrv, "fshsrv/mp/updateMerchant", data);
}

export function queryShops(sortType, pageNum) {
  return request.get(fshsrv, "fshsrv/mp/queryShops", {sortType, pageNum}, {noAuth:true});
}

export function openShop(id) {
  return request.get(fshsrv, "fshsrv/mp/openShop", {id}, {noAuth:true});
}

export function addShop(data) {
  return request.post(fshsrv, "fshsrv/mp/addShop", data);
}

export function modifyShop(data) {
  return request.post(fshsrv, "fshsrv/mp/modifyShop", data);
}

export function getMyShops(id, pageNum) {
	id = id ? id : 0;
  return request.get(fshsrv, "fshsrv/mp/getMyShops", {id, pageNum});
}

export function delMyShop(id) {
  return request.post(fshsrv, "fshsrv/mp/delMyShop", {id});
}

export function addShopComplaint(data) {
  return request.post(fshsrv, "fshsrv/mp/addShopComplaint", data);
}

export function batchPause(pondId, partitionId, fromSeatNo, toSeatNo, isPause) {
	isPause = isPause?1:0;
  return request.get(fshsrv, "gzyxsrv/mp/batchPause", {pondId, partitionId, fromSeatNo, toSeatNo, isPause});
}

export function batchStop(pondId, partitionId, fromSeatNo, toSeatNo) {
  return request.get(fshsrv, "gzyxsrv/mp/batchStop", {pondId, partitionId, fromSeatNo, toSeatNo});
}

export function batchReset(pondId, partitionId, fromSeatNo, toSeatNo) {
  return request.get(fshsrv, "gzyxsrv/mp/batchReset", {pondId, partitionId, fromSeatNo, toSeatNo});
}

export function addStock(productId, sku, stock) {
  return request.get(fshsrv, "gzyxsrv/mp/prodct/addStock", {productId, sku, stock});
}

export function getSkuForAddStock(productId) {
  return request.get(fshsrv, "gzyxsrv/mp/prodct/getSkuForAddStock", {productId});
}

export function getMerBossData(merId) {
	return request.get(fshsrv, "fshsrv/mp/getMerBossData", {merId});
}

export function getMerDayOrders(merId, fromDay, needTbHeader) {
	needTbHeader = needTbHeader?1:0;
	return request.get(fshsrv, "fshsrv/mp/getMerDayOrders", {merId, fromDay, needTbHeader});
}

export function getMerBalance(merId, type=1) { // type: 1-基本账户，其它-保证金账户
	return request.get(fshsrv, "fshsrv/mp/getMerBalance", {merId, type});
}

export function merExtractApply(merId, extractMoney) {
	return request.get(fshsrv, "fshsrv/mp/merExtractApply", {merId, extractMoney});
}

export function getMerExtractList(merId) {
	return request.get(fshsrv, "fshsrv/mp/getMerExtractList", {merId});
}

export function getMerBills(merId, day) {
	return request.get(fshsrv, "fshsrv/mp/getMerBills", {merId, day});
}

export function getMerRechargeList(merId) {
	return request.get(fshsrv, "fshsrv/mp/getMerRechargeList", {merId});
}

export function debugDevice(pondId, partitionId, seatIds, action) {
  return request.get(fshsrv, "gzyxsrv/device/debugDevice", {pondId, partitionId, seatIds, action});
}

export function superAdminGetOperations() {
  return request.get(fshsrv, "gzyxsrv/mp/superAdminGetOperations");
}

export function superAdminDoOperation(jsonParam) {
  return request.get(fshsrv, "gzyxsrv/mp/superAdminDoOperation", jsonParam);
}

export function updateUserNickname(uid, nickname, avatarUrl) {  // php: C:\mysvn\ssty\multi-merchant\mallsrv170\app\controller\api\Auth.php::userInfo
	return request.get(fshsrv, 'fshsrv/mp/updateNicknameAvatar', {uid, nickname, avatarUrl});
}
